#include <nxos.h>

typedef NX_Error (*TestFuncHandler) (char *cmd);
typedef struct {
    char *name;
    TestFuncHandler func;
} TestFunc;

NX_IMPORT NX_Error TEST_ExecuteMe(char *cmdline);
NX_IMPORT NX_Error TEST_Syscall(char *cmdline);
NX_IMPORT NX_Error TEST_MemMan(char *cmdline);
NX_IMPORT NX_Error TEST_Args(char *cmdline);
NX_IMPORT NX_Error TEST_Snapshot(char *cmdline);
NX_IMPORT NX_Error TEST_Time(char *cmdline);
NX_IMPORT NX_Error TEST_WastCpu(char *cmdline);
NX_IMPORT NX_Error TEST_Thread(char *cmdline);
NX_IMPORT NX_Error TEST_TLS(char *cmdline);
NX_IMPORT NX_Error TEST_Device(char *cmdline);
NX_IMPORT NX_Error TEST_Signal(char *cmdline);
NX_IMPORT NX_Error TEST_Timer(char *cmdline);
NX_IMPORT NX_Error TEST_Stack(char *cmdline);
NX_IMPORT NX_Error TEST_Udriver(char *cmdline);
NX_IMPORT NX_Error TEST_PollWait(char *cmdline);
NX_IMPORT NX_Error TEST_Shm(char *cmdline);
NX_IMPORT NX_Error TEST_Fifo(char *cmdline);
NX_IMPORT NX_Error TEST_Atomic(char *cmdline);
NX_IMPORT NX_Error TEST_Spin(char *cmdline);
NX_IMPORT NX_Error TEST_Condition(char *cmdline);
NX_IMPORT NX_Error TEST_Pipe(char *cmdline);
NX_IMPORT NX_Error TEST_Trace(char *cmdline);

#define TEST_FUNC "execme"

NX_PRIVATE TestFunc testTable[] = {
    {"snapshot", TEST_Snapshot},
    {"execme", TEST_ExecuteMe},
    {"syscall", TEST_Syscall},
    {"mman", TEST_MemMan},
    {"args", TEST_Args},
    {"time", TEST_Time},
    {"wastcpu", TEST_WastCpu},
    {"thread", TEST_Thread},
    {"tls", TEST_TLS},
    {"device", TEST_Device},
    {"signal", TEST_Signal},
    {"timer", TEST_Timer},
    {"stack", TEST_Stack},
    {"udriver", TEST_Udriver},
    {"pollwait", TEST_PollWait},
    {"shm", TEST_Shm},
    {"fifo", TEST_Fifo},
    {"atomic", TEST_Atomic},
    {"spin", TEST_Spin},
    {"condition", TEST_Condition},
    {"pipe", TEST_Pipe},
    {"trace", TEST_Trace},
};

NX_Error NX_Main(char *cmdline, char *envline)
{
    NX_Error err;
    int i;
    char *argv[16] = {0};
    int argc;
    char * testName;
    char ** newArgv;
    int newArgc = 1;
    char newCmdline[512];
    
    argc = NX_CmdToArray(cmdline, argv, 16);
    
    if (argc > 1) /* has test app */
    {
        testName = argv[1];
        
        newArgv = &argv[1];
    }
    else
    {
        testName = TEST_FUNC;

        argv[1] = TEST_FUNC;
        newArgv = &argv[1];
    }

    newArgc = NX_CmdToBuf(newCmdline, 512, newArgv);
    if (newArgc < 1)
    {
        NX_Printf("cmd to buf error!\n");
        return NX_ERROR;
    }

    NX_Printf("user test start.\n");
    for (i = 0; i < NX_ARRAY_SIZE(testTable); i++)
    {
        if (!NX_StrCmp(testTable[i].name, testName))
        {
            err = testTable[i].func(newCmdline);
            break;
        }
    }
    if (i >= NX_ARRAY_SIZE(testTable))
    {
        err = testTable[0].func(newCmdline); /* execute first func */
    }
    NX_Printf("\nuser test done.\n");
    return err;
}
